<template>
    <div>
        <el-row :gutter="10" v-if="!check_status && !settlement_status">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-card>
                    <template #header>
                        <div style="font-size: 20px; font-weight: 600;">
                            <span>房间管理</span>
                        </div>
                        <div style="height: 2vh;"></div>
                        <div style="display:flex;justify-content:space-between;">
                            <div style="display: flex;align-items: center;">
                                <div style="width: 15px;"></div>
                                <el-select v-model="value" class="m-2" placeholder="房间状态选择" @change="seach" clearable>
                                    <el-option label="有人" value="2" />
                                    <el-option label="空闲" value="1" />
                                </el-select>
                                <div style="width: 15px;"></div>
                                <div style="display: flex;align-items: center;">
                                    <el-input v-model="room_select" placeholder="输入房间号" @input="seach" clearable
                                        style="width:250px" />
                                    <div style="width: 8px;"></div>
                                </div>
                                <div style="width: 10px;"></div>
                                <div style="display: flex;align-items: center;">
                                    <el-input v-model="bed_select" placeholder="输入床号" @input="seach" clearable
                                        style="width:250px" />
                                    <div style="width: 8px;"></div>
                                </div>
                                <div style="width: 10px;"></div>
                                <el-select v-model="depart_value" class="m-2" filterable placeholder="科室选择" @change="seach"
                                    clearable>
                                    <el-option v-for="item in options" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </div>
                            <div class="right">
                                <el-button type="primary" @click="addOffice">新增房间</el-button>
                            </div>
                        </div>
                    </template>
                    <div v-if="room_value.length == 0 && !loadinng" style="width: 100%;text-align: center;">
                        <el-empty description="暂无数据" />
                    </div>
                    <div class="room_box" v-loading="loadinng">
                        <div class="room_list" v-for="(item, index) in room_value" :key="index"
                            @contextmenu.prevent="edit(item)">

                            <el-image :src="url + item.img" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                                :preview-src-list="[url + item.img]" fit="cover" preview-teleported="true"
                                style="width: 80px;height: 80px;border-radius: 5%;" />


                            <!-- <img :src="'https:/lxt.jingyi.icu' + item.img" alt=""> -->
                            <div class="room_zhong">
                                <p class="room_top"> <span style="color: #8C83FF;">{{ item.room_num }}号房间</span>
                                    <el-tooltip class="box-item" effect="dark" :content="item.detart_name"
                                        placement="top"><span
                                            style="display: block; width: 50px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                            {{ item.detart_name }} </span>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" :content="item.bed_num
                                    +'床'"
                                        placement="top">
                                    <span style="color: #8C83FF;">{{ item.bed_num
                                    }}</span>
                                    </el-tooltip>
                                </p>
                                <div>
                                    <p :style="item.room_status == 1 ? 'color: #67C23A;' : 'color:red;'">{{
                                        item.room_status == 1 ? '空房' : '有人' }}</p>
                                    <p>{{ item.hospital_status == 1 ? '欠费' : item.hospital_status == 2 ? '住院中' : '' }}</p>
                                </div>
                                <p style="color: #999999;"> 添加时间：{{ item.create_time }} </p>
                            </div>
                            <div class="but">
                                <div> <el-button size="small" type="primary" plain
                                        :disabled="item.room_status == 1 ? true : false" @click="check(item)">查房</el-button>
                                </div>
                                <div> <el-button size="small" type="primary" plain
                                        :disabled="item.room_status == 1 ? true : false"
                                        @click="settlement(item)">结算</el-button></div>
                                <div> <el-button size="small" type="primary" plain
                                        :disabled="item.room_status == 1 ? false : true"
                                        @click="set_room(item)">住院</el-button></div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-row :gutter="10" v-if="check_status || settlement_status">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <div style="display: flex;align-items: center;justify-content: space-between;">
                    <div class="top_navigate">
                        <el-button type="primary" :icon="ArrowLeftBold"
                            @click="check_status = false, index = 1, settlement_status = false">返回</el-button>
                    </div>
                    <div>&nbsp;</div>
                </div>
                <div style="height: 15px;"></div>
                <el-card class="box-card">
                    <template #header>
                        <div class="card-header">
                            <span>患者信息</span>
                        </div>
                    </template>
                    <div v-if="visit_value.length != 0">
                        <div class="arrow">
                            <div class="user_inp">
                                <div style="width: 120px;color:#afafaf;">患者姓名</div>
                                <div>{{ visit_value.nickname }}</div>
                            </div>
                            <div class="user_inp">
                                <div style="width: 120px;color:#afafaf;">性别</div>
                                <div v-if="visit_value.sex == 1">男</div>
                                <div v-else-if="visit_value.sex == 2">女</div>
                            </div>
                            <div class="user_inp">
                                <div style="width: 120px; color: #afafaf;">账户头像</div>
                                <el-image :src="visit_value.avatar" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                                    :preview-src-list="[visit_value.avatar]" fit="cover" preview-teleported="true"
                                    style="width: 75px; height: 75px; border-radius: 180%;" />
                            </div>
                        </div>
                        <div class="arrow">
                            <div class="user_inp">
                                <div style="width: 120px;color:#afafaf;">证件类型</div>
                                <div>身份证</div>
                            </div>
                            <div class="user_inp">
                                <div style="width: 120px;color:#afafaf;">证件号码</div>
                                <div>{{ visit_value.code }}</div>
                            </div>
                            <div class="user_inp">
                                <div style="width: 120px;color:#afafaf;">就诊时间</div>
                                <div>{{ visit_value.create_time }}</div>
                            </div>
                        </div>
                        <div class="arrow">
                            <div class="user_inp">
                                <div style="width: 120px;color:#afafaf;">就诊人地址</div>
                                <div>{{ visit_value.address }}</div>
                            </div>
                            <div class="user_inp">
                                <div style="width: 120px;color:#afafaf;">手机号</div>
                                <div>{{ visit_value.tel }}</div>
                            </div>
                            <div class="user_inp">
                                <div style="width: 120px;color:#afafaf;">关系</div>
                                <div>{{ visit_value.relationship }}</div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-row :gutter="10" v-if="check_status" style="margin-top: 20px;">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-card class="box-card">
                    <template #header>
                        <div class="card-header">
                            <span>查房记录</span>
                        </div>
                    </template>
                    <div style="display: flex;">
                        <el-timeline>
                            <el-timeline-item class="barground" :type="indexs != 0 ? 'primary' : ''" hollow="true"
                                :color="indexs != activities.length - 1 && indexs != 0 ? '#006EFF' : indexs == 0 ? '#0bbd87' : ''"
                                :style="indexs == 0 ? '' : 'cursor:pointer;'" :class="index == indexs ? 'bar' : ''"
                                v-for="(activity, indexs) in activities" :key="indexs" @click="click(activity, indexs)"
                                :timestamp="activity.timestamp">
                                {{ activity.content }}
                            </el-timeline-item>
                        </el-timeline>
                        <div v-if="index > 0">
                            <div class="form">
                                <p> <span>房间号&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                                        room_num }}号房间
                                </p>
                                <p> <span>住院状态</span>
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;住院中
                                </p>
                                <p><span>科室名称</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                                    detart_name }}
                                </p>
                                <p><span>住院原因</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                                    form.reason }}
                                </p>
                                <p><span>查房医生</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<el-input
                                        style="display:block;width:auto;margin:0px 10px;" v-model="check_data.name"
                                        placeholder="请输入" />
                                </p>
                                <p style="display:flex;">
                                    <span>查房次数</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;第
                                    <el-input disabled="true" style="display:block;width:30px;margin:0px 10px;"
                                        v-model="check_data.day" />次查房
                                </p>
                            </div>
                            <div class="forms">
                                <p><span>体温&nbsp;&nbsp;&nbsp;&nbsp;</span><el-input
                                        style="display:block;width:100px;margin:0px 10px;" type="number"
                                        v-model="check_data.temperature" placeholder="请输入" />
                                </p>
                                <p><span>呼吸&nbsp;&nbsp;&nbsp;&nbsp;</span><el-input
                                        style="display:block;width:100px;margin:0px 10px;" type="number"
                                        v-model="check_data.breathe" placeholder="请输入" />次/分
                                </p>
                                <p><span>心率&nbsp;&nbsp;&nbsp;&nbsp;</span><el-input
                                        style="display:block;width:100px;margin:0px 10px;" type="number"
                                        v-model="check_data.rate" placeholder="请输入" />次/分
                                </p>
                                <p><span>血压&nbsp;&nbsp;&nbsp;&nbsp;</span><el-input
                                        style="display:block;width:100px;margin:0px 10px;" type="number"
                                        v-model="check_data.blood" placeholder="请输入" /> mmHg
                                </p>
                            </div>
                            <div class="note">
                                <p><span>查房备注</span>
                                    <el-input v-model="check_data.note" maxlength="100" show-word-limit type="textarea"
                                        placeholder="请输入" :autosize="{ minRows: 4, maxRows: 6 }" />
                                </p>
                                <div class="button">
                                    <el-button type="primary" @click="save">保存</el-button>
                                    <el-button type="warning" @click="restore">恢复</el-button>
                                    <el-button type="danger" @click="reset">重置</el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-row :gutter="10" style="margin-top: 20px;" v-if="settlement_status">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-card class="box-card">
                    <template #header>
                        <div class="card-header">
                            <span>费用明细</span>
                        </div>
                    </template>
                    <div style="display:flex;">
                        <el-timeline style="width:15%;">
                            <el-timeline-item class="barground" :type="indexs != 0 ? 'primary' : ''" hollow="true"
                                :color="indexs != activities.length - 1 && indexs != 0 ? '#006EFF' : indexs == 0 ? '#0bbd87' : ''"
                                :style="indexs == 0 ? '' : 'cursor:pointer;'" :class="day == indexs ? 'bar' : ''"
                                v-for="(activity, indexs) in activities" :key="indexs" @click="Settlement(activity, indexs)"
                                :timestamp="activity.timestamp">
                                {{ activity.content }}
                            </el-timeline-item>
                        </el-timeline>
                        <div style="margin-left:40px;width:80%;">
                            <div
                                style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 20px;">
                                <el-button type="primary" @click="add"
                                    :disabled="day != activities.length - 1 ? true : false">新增服务</el-button>
                                <el-button type="success" @click="discharge"
                                    v-if="day == activities.length - 1">出院</el-button>
                            </div>
                            <div style="width: 100%;">
                                <el-table ref="multipleTableRef" style="width: 100%" stripe border size="large"
                                    :data="zhangdetailed.slice((currentPage5 - 1) * pageSize5, currentPage5 * pageSize5)"
                                    v-loading="loadings" max-height="25vh">
                                    <el-table-column label="序号" property="id" width="120" align="center" />
                                    <el-table-column property="name" label="服务名称" width="200" align="center" />
                                    <el-table-column label="服务类型" property="type" width="140" align="center">
                                        <template #default="scope">
                                            {{ scope.row.type === 1 ? '药品' : (scope.row.type === 2 ? '体检' : '住院费') }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column property="price" label="单价(元)" show-overflow-tooltip align="center" />
                                    <el-table-column property="number" label="规格" show-overflow-tooltip align="center" />
                                    <el-table-column property="money" label="小计(元)" show-overflow-tooltip align="center" />
                                    <el-table-column label="订单状态" show-overflow-tooltip align="center">
                                        <template #default="scope">
                                            <span v-if="scope.row.status === 1" style="color: rgb(43, 207, 43);"><el-tag
                                                    class="ml-2" type="success">已支付</el-tag></span>
                                            <span v-else-if="scope.row.status === 2" style="color: red;"><el-tag
                                                    class="ml-2" type="danger">未支付</el-tag></span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" width="150" align="center">
                                        <template #default="scope">
                                            <div style="display: flex; align-items: center;justify-content: center;">
                                                <el-button type="primary" plain size="small"
                                                    :disabled="scope.row.name == '住院费'"
                                                    @click="centerDialogVisible(scope.row.id, scope.row)">编辑</el-button>
                                                <el-button type="danger" plain size="small"
                                                    :disabled="scope.row.name == '住院费'"
                                                    @click="clocks(scope.row.id)">删除</el-button>
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <div style="height: 1vh;"></div>
                                <div style="display:flex;justify-content: center;">
                                    <el-pagination v-model:current-page="currentPage5" v-model:page-size="pageSize5"
                                        :page-sizes="[10, 20, 50, 100]" :small="small" :disabled="disabled"
                                        :background="background" layout="total, sizes, prev, pager, next, jumper"
                                        :total="zhangdetailed.length" />
                                </div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog v-model="discharge_status" title="上传体检结果和图片" :close-on-press-escape="false" :close-on-click-modal="false"
            :show-close="false">
            <el-form ref="results" :model="result_data" :rules="result" label-width="80px" class="demo-ruleForm"
                :size="formSize" status-icon>
                <div v-for="(item, index) in zhangdetailed" :key="index" :title="item.name">
                    <el-form-item :label="item.name" :prop="'result' + index" v-if="item.type == 2">
                        <el-input v-model="result_data['result' + index]" placeholder="体检结果" />
                    </el-form-item>
                    <el-form-item :prop="'img' + index" v-if="item.type == 2">
                        <el-upload class="avatar-uploader" action="https://lxt.jingyi.icu/pc/Fileimg/file"
                            :show-file-list="false" :on-success="handleAvatarSucces" :before-upload="beforeAvatarUpload">
                            <img @click="setindex(index)" v-if="result_data['img' + index]"
                                :src="url + result_data['img' + index]" class="avatar" />
                            <el-icon @click="setindex(index)" v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </div>
                <div style="direction: rtl;">
                    <el-form-item>
                        <el-button type="primary" @click="result_submitForm(results)">
                            确认
                        </el-button>
                        <div style="height: 10px;width: 10px;"></div>
                        <el-button @click="result_resetForm(results)">取消</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog v-model="centerDialogVisibles" :title="title" width="40%" align-center :close-on-press-escape="false"
            :close-on-click-modal="false" :show-close="false">
            <div>
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm"
                    :size="formSize" status-icon>
                    <el-form-item label="服务类型" prop="name">
                        <el-select v-model="ruleForm.name" placeholder="请选择服务类型" @change="types">
                            <el-option label="体检" value="2" />
                            <el-option label="药品" value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="服务名称" prop="region">
                        <el-select v-model="ruleForm.region" placeholder="请选择服务名称" @change="fw_name" :disabled="disableds">
                            <el-option v-for="item in drugLists" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="规格" prop="count">
                        <el-input v-model="ruleForm.count" placeholder="请输入规格" @input="guig(ruleForm.count)" />
                    </el-form-item>
                    <el-form-item label="单价" prop="">
                        <el-input :value="prices_name" placeholder="选择服务名称后自动填充" readonly />
                    </el-form-item>
                    <el-form-item label="总计" prop="" v-if="inp_zj">
                        <el-input :value="prices_all" placeholder="选择服务名称后自动填充" readonly />
                    </el-form-item>
                    <div style="direction: rtl;">
                        <el-form-item>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">
                                确认
                            </el-button>
                            <div style="height: 10px;width: 10px;"></div>
                            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
        </el-dialog>
        <!-- 新增/编辑页面 -->
        <el-dialog v-model="dialogFormVisible" :title="room_title" @close="cancel()" width="40%">
            <div class="window">
                <el-form ref="ruleFormRefs" :model="formd" :rules="rule" label-width="100px" label-position="right">
                    <div class="inpuut_box">
                        <div class="">
                            <el-form-item label="选择科室" prop="department">
                                <el-select v-model="formd.department" clearable placeholder="请选择科室">
                                    <el-option v-for="item in departList" :label="item.name" :value="item.id"
                                        :key="item.id" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="房间号" prop="room_num">
                                <el-input v-model="formd.room_num" placeholder="输入房间号" type="number" />
                            </el-form-item>
                            <el-form-item label="床号" prop="bed_num">
                                <el-input v-model="formd.bed_num" placeholder="输入床号" type="number" />
                            </el-form-item>
                            <el-form-item label="就诊卡号" prop="card">
                                <el-input v-model="formd.card" placeholder="输入就诊卡号" type="number" />
                            </el-form-item>
                            <el-form-item label="状态" prop="status">
                                <el-switch v-model="formd.room_status" />
                            </el-form-item>
                            <el-form-item label="图片" prop="img">
                                <el-upload class="avatar-uploader" :action="url + 'pc/Fileimg/file'" :show-file-list="false"
                                    :on-success="handleAvatarSuccess" :on-error="uploadError">
                                    <img v-if="formd.img" :src="url + formd.img" class="avatar" />
                                    <el-icon v-else class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                            </el-form-item>
                        </div>
                    </div>
                    <div style="direction: rtl;">
                        <el-form-item>
                            <el-button type="primary" @click="affirm(ruleFormRefs)">保存</el-button>
                            <div style="width: 10px;"></div>
                            <el-button @click="cancel(ruleFormRefs)">取消</el-button>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
        </el-dialog>
        <el-dialog v-model="room_status" title="添加住院人" width="40%" align-center :close-on-press-escape="false"
            :close-on-click-modal="false" :show-close="false">
            <div>
                <el-form ref="rooms" :model="room_ruleForm" :rules="room_rule" label-width="100px" class="demo-ruleForm"
                    :size="formSize" status-icon>
                    <el-form-item label="选择就诊卡" prop="card">
                        <el-select v-model="room_ruleForm.card" placeholder="请选择就诊卡">
                            <el-option v-for="(item, index) in visit_data" :key="index" :label="item.nickname"
                                :value="item.card" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="住院原因" prop="reason">
                        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="room_ruleForm.reason">
                        </el-input>
                    </el-form-item>
                    <div style="direction: rtl;">
                        <el-form-item>
                            <el-button type="primary" @click="room_yes(rooms, item)">
                                确认
                            </el-button>
                            <div style="height: 10px;width: 10px;"></div>
                            <el-button @click="room_cancel(rooms)">取消</el-button>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { Outpatientpayment, Outpatientxq, ZDdetailed, Drug, Tlmin, Closed, Tlist, room_hospital } from '@/api/user'
import { room_list, Settlement_list, Settlement_del, Settlement_add, room_add, discharge_edit } from '@/api/hospital';
import { ArrowLeftBold } from '@element-plus/icons-vue'
import { visit, check_list, check_add, visit_detail } from '@/api/visit'
import { depart } from '@/api/departMents'
import { Plus } from '@element-plus/icons-vue';
import { ref } from 'vue';
const check_status = ref(false)//查房页面显示状态
const settlement_status = ref(false)//结算页面显示状态
const value = ref()//房间状态选择
const room_status = ref(false)//住院弹出框
const room_num = ref()//房间号
const loadinng = ref(true)
// const room = ref()
const discharge_status = ref(false)
const bed_num = ref()//床号
const url = ref('https://lxt.jingyi.icu/'); //域名头
const options = ref([])//科室
const room_value = ref()//房间列表
const search_value = ref()//搜索数据
const visit_value = ref()//就诊卡详情
const check_list_value = ref();//查房记录
const activities = ref([])//查房记录时间线
const index = ref(0)//时间线的背景色
const visit_data = ref()//就诊卡列表
const room_select = ref()//搜索的房间号
const bed_select = ref()//搜索的床号
const id = ref();//保存用的id
const day = ref(1)//结算的天数
const depart_value = ref()//科室
const zhangdetailed = ref([])
const room_data = ref()//房间的数据
const room_title = ref('新增房间信息')
const departList = ref([]); //科室列表
const inp_zj = ref(false)
const currentPage5 = ref(1)
const dialogFormVisible = ref(false)
const loadings = ref(false)
const centerDialogVisibles = ref(false)
const pageSize5 = ref(10)
const drugLists = ref([])
const zong = ref('')
const bianvalue = ref('')
const title = ref('编辑')
const prices_all = ref();
const formSize = ref('default');
const zangxid = ref('')
const card = ref()
const room_id = ref()
const bed = ref()
const result = ref({})//体检图片的效验效果
const result_data = ref({})
const index_img = ref()//上传图片的下标
const number = ref()//需要上传体检结果的数量
const ruleFormRef = ref('');
const ruleFormRefs = ref();
const results = ref('')// 接口数据

// const result_resetForm = (foms) => {
// console.log(foms);
//     setTimeout(() => {
//         foms.clearValidate();
//     }, 20);
// }
const result_resetForm = (foms) => {
    console.log(foms);
    if (!foms) return;
    let array = []
    for (let i in zhangdetailed.value) {
        if (zhangdetailed.value[i].type == 2) {
            array.push(zhangdetailed.value[i].name)
            result.value['result' + i] = [
                {
                    required: true,
                    message: '请输入体检结果',
                    trigger: 'change'
                }
            ]
            result_data.value['result' + i] = ''
            result_data.value['img' + i] = ''
            result_data.value['name'] = zhangdetailed.value[i].name
            result.value['img' + i] = [
                {
                    required: true,
                    message: '请上传图片',
                    trigger: 'change'
                }
            ]
        }
    }
    number.value = array
    setTimeout(() => {
        foms.resetFields();
    }, 10);
    discharge_status.value = false
};
const result_submitForm = async (foms) => {
    console.log(foms);
    if (!foms) return;
    await foms.validate((valid, fields) => {
        if (valid) {
            ElMessageBox.confirm('是否确认让该用户出院?', '办理出院', {
                confirmButtonText: '已痊愈，可以出院',
                cancelButtonText: '还未痊愈，不能出院',
                type: 'warning',
            })
                .then(() => {
                    let array = []
                    for (let i = 0; i < number.value.length; i++) {
                        array.push({
                            result: result_data.value['result' + (i + 1)],
                            img: result_data.value['img' + (i + 1)],
                            name: number.value[i]
                        })
                    }
                    discharge_status.value = false
                    setTimeout(() => {
                        foms.clearValidate();
                    }, 20);
                    discharge_edit({
                        card: card.value,
                        bed_num: bed_num.value,
                        room_id: room_id.value,
                        room_num: room_num.value,
                        arr: JSON.stringify(array)
                    }).then((res) => {
                        if (res.code == 1) {
                            ElMessage({
                                type: 'success',
                                message: '出院成功',
                            });
                            settlement_status.value = false
                            box()
                        } else {
                            ElMessage({
                                type: 'error',
                                message: res.msg,
                            });
                        }
                    }).catch((res) => {
                        ElMessage({
                            type: 'error',
                            message: res.msg,
                        });
                    })
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '未出院',
                    });
                });
        } else {
            console.log('error submit!', fields);
        }
    })
}
const handleAvatarSucces = (response, uploadFile) => {
    result_data.value['img' + index_img.value] = response.data.url
};
const setindex = (index) => {
    index_img.value = index
}
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('大小不能超过2MB');
        return false;
    }
    return true;
};
const handleAvatarSuccess = (response, uploadFile) => {
    console.log(response);
    formd.value.img = response.data.url;
};
const uploadError = (error, uploadFile) => {
    formd.value.img = response.data.url;
};
const room_ruleForm = ref({
    card: '',
    reason: ''
})
const set_room = (item) => {
    room_status.value = true
    room_data.value = item
}
const room_rule = {
    card: [
        {
            required: true,
            message: '请输入选择就诊卡',
            trigger: 'change'
        },
    ],
    reason: [
        {
            required: true,
            message: '请输入住院原因',
            trigger: 'change'
        },
    ]
}

const rooms = ref('')
const room_yes = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            room_hospital({
                room_num: room_data.value.room_num,
                bed_num: room_data.value.bed_num,
                room_status: 2,
                card: room_ruleForm.value.card,
                hospital_status: 2,
                reason: room_ruleForm.value.reason,
                id: room_data.value.id,
                department: room_data.value.department
            }).then((res) => {
                if (res.code == 1) {
                    ElMessage({
                        type: 'success',
                        message: '添加成功',
                    });
                    room_status.value = false
                    room_ruleForm.value.card = ''
                    room_ruleForm.value.reason = ''
                    setTimeout(() => {
                        room.clearValidate();
                    }, 20);
                    box()
                } else {
                    ElMessage({
                        type: 'error',
                        message: res.msg,
                    });
                }
            }).catch((res) => {
                ElMessage({
                    type: 'error',
                    message: res.msg,
                });
            })

        } else {
            console.log('error submit!', fields);
        }
    });
};


const room_cancel = (formEl) => {
    console.log(formEl);
    if (!formEl) return;
    room_rule.value = {
        card: '',
        reason: ''
    }
    setTimeout(() => {
        formEl.resetFields();
    }, 10);
    room_status.value = false
}

const form = reactive({
    room_num: '', //房间号ID
    bed_num: '', //床号
    img: '',//图片
    room_status: true,//状态
    card: '', //就诊卡号
    id: '', //编辑医生id
    department: '', //科室
});
const discharge = () => {
    let array = []
    for (let i in zhangdetailed.value) {
        if (zhangdetailed.value[i].type == 2) {
            array.push(zhangdetailed.value[i].name)
            result.value['result' + i] = [
                {
                    required: true,
                    message: '请输入体检结果',
                    trigger: 'change'
                }
            ]
            result_data.value['result' + i] = ''
            result_data.value['img' + i] = ''
            result_data.value['name'] = zhangdetailed.value[i].name
            result.value['img' + i] = [
                {
                    required: true,
                    message: '请上传图片',
                    trigger: 'change'
                }
            ]
        }
    }
    console.log(array, 777);
    if (array.length == 0) {
        ElMessageBox.confirm('是否确认让该用户出院?', '办理出院', {
            confirmButtonText: '已痊愈，可以出院',
            cancelButtonText: '还未痊愈，不能出院',
            type: 'warning',
        })
            .then(() => {
                discharge_status.value = false
                discharge_edit({
                    card: card.value,
                    bed_num: bed_num.value,
                    room_id: room_id.value,
                    room_num: room_num.value,
                }).then((res) => {
                    if (res.code == 1) {
                        ElMessage({
                            type: 'success',
                            message: '出院成功',
                        });
                        settlement_status.value = false
                        box()
                    } else {
                        ElMessage({
                            type: 'error',
                            message: res.msg,
                        });
                    }
                }).catch((res) => {
                    ElMessage({
                        type: 'error',
                        message: res.msg,
                    });
                })
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '未出院',
                });
            });
        return
    }
    number.value = array
    setTimeout(() => {

        discharge_status.value = true
    }, 20);
}
const formd = ref({
    room_num: '', //房间号ID
    bed_num: '', //床号
    img: '',//图片
    room_status: true,//状态
    card: '', //就诊卡号
    id: '', //编辑医生id
    department: '', //科室
});
const rule = {
    room_num: [
        {
            required: true,
            message: '请输入房间号',
            trigger: 'change'
        },
        { pattern: /^\d{1,3}$/, message: '无此房间', trigger: 'change' }
    ],
    bed_num: [
        {
            required: true,
            message: '请输入床号',
            trigger: 'change'
        },
        { pattern: /^[1-4]$/, message: '床号只存在1至4床', trigger: 'change' }
    ],
    img: [
        {
            required: true,
            message: '请上传图片',
            trigger: 'change'
        },
    ],
    card: [
        {
            required: true,
            message: '请输入就诊卡号',
            trigger: 'change'
        },
        { pattern: /^\d{16}$/, message: '标准就诊卡号应为16位数', trigger: 'change' }
    ],
    department: [
        {
            required: true,
            message: '请选择科室',
            trigger: 'change'
        },
    ]
}
// 确认新增/编辑科室
const affirm = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid, fields) => {
        console.log(valid);
        if (valid) {

            room_add(formd.value).then((res) => {
                if (res.code == 1) {
                    ElMessage({
                        type: 'success',
                        message: '添加成功',
                    });
                    box()
                    formd.value = ({
                        room_num: '', //房间号ID
                        bed_num: '', //床号
                        img: '',//图片
                        room_status: true,//状态
                        card: '', //就诊卡号
                        id: '', //编辑医生id
                        department: '', //科室
                    });
                    setTimeout(() => {
                        formEl.clearValidate();
                    }, 20);
                } else {
                    ElMessage({
                        type: 'error',
                        message: '添加失败',
                    });
                }

                dialogFormVisible.value = false
                requestList();

            });

        } else {
            console.log('error submit!', fields);
        }
    });
}
// 确认新增/编辑科室
// const affirm = async (formEl) => {
//     if (!formEl) return;
//     await formEl.validate((valid, fields) => {
//         if (valid) {


//     } else {
//         console.log('error submit!', fields);
//       }
//     })


// };
// const cancel = (formEl) => {
//     if (formEl) return;
//     formd.value({
//         room_num: '', //房间号ID
//         bed_num: '', //床号
//         img: '',//图片
//         room_status: true,//状态
//         card: '', //就诊卡号
//         id: '', //编辑医生id
//         department: '', //科室
//     });

//     setTimeout(() => {
//         room.clearValidate();
//     }, 20);
// }
const cancel = (forse) => {
    console.log(forse);
    if (!forse) return;
    formd.value = ({
        room_num: '', //房间号ID
        bed_num: '', //床号
        img: '',//图片
        room_status: true,//状态
        card: '', //就诊卡号
        id: '', //编辑医生id
        department: '', //科室
    });
    setTimeout(() => {
        forse.resetFields();
    }, 10);
    dialogFormVisible.value = false

};
const edit = (item) => {
    dialogFormVisible.value = true
    room_title.value = '编辑房间信息'
    formd.value.id = item.id;
    formd.value.room_num = item.room_num
    formd.value.bed_num = item.bed_num
    formd.value.department = item.department
    formd.value.card = item.card
    formd.value.img = item.img
}
const addOffice = () => {
    room_title.value = '新增房间信息'
    formd.value.id = '';
    formd.value.room_num = ''
    formd.value.bed_num = ''
    formd.value.department = ''
    formd.value.card = ''
    formd.value.img = ''
    // ruleFormRefs.value.clearValidate();
    dialogFormVisible.value = true
}
// 请求列表
const requestList = async () => {
    try {
        const ress = await depart();
        //科室选择只选子集
        let data = [];
        for (let i = 0; i < ress.data.length; i++) {
            if (ress.data[i].pid != 0) {
                data.push(ress.data[i]);
            }
        }
        departList.value = data;
    } catch (error) {
        console.error(error);
    }
};
requestList();
const ruleForm = ref(
    {
        name: '',
        region: '',
        count: '',
        // date1: '',
    }
)
function guig(e) {
    console.log(e);
    bianvalue.value = e
    prices_all.value = e * zong.value
}
function drap() {
    Drug().then((res) => {
        const drugList = res.data.map(drug => {
            return { name: drug.name, id: drug.id, price: drug.price };
        });
        drugLists.value = drugList
        if (drugLists.value || drugLists.value.length == 0) {
            fw_name(ruleForm.value.region);
        }
    })
}
const dele = () => {
    console.log(23);
}

const prices_name = ref();
const disableds = ref(false);
const rules = {
    name: [
        {
            required: true,
            message: '请选择服务类型',
            trigger: 'change'
        },
    ],
    region: [
        {
            required: true,
            message: '请选择服务名称',
            trigger: 'change',
        },
    ],
    count: [
        {
            required: true,
            message: '请输入规格',
            trigger: 'change',
        },
    ],
};
function fw_name(e) {
    const prices = drugLists.value
        .filter(drug => drug.id == e)
        .map(drug => drug.price);
    prices_name.value = prices[0]
    if (ruleForm.value.count != '') {
        prices_all.value = prices_name.value * ruleForm.value.count
    } else {
        prices_all.value = prices_name.value
        ruleForm.value.count = 1
    }
    zong.value = prices_name.value
    if (prices_name.value == '' || prices_name.value == undefined) {
        inp_zj.value = false
        ruleForm.value.count = ''
    } else {
        if (e != '' || e != undefined) {
            ruleForm.value.count = ruleForm.value.count
        } else {
            ruleForm.value.count = 1
        }
        inp_zj.value = true
    }
}
function tix() {
    Tlist().then((res) => {
        const drugList = res.data.map(drug => {
            return { name: drug.name, id: drug.id, price: drug.price };
        });
        drugLists.value = drugList
        if (drugLists.value || drugLists.value.length == 0) {
            fw_name(ruleForm.value.region);
        }
    })
}
function types(e) {
    if (e == 1) {
        disableds.value = false
        drap()
    } else {
        tix()
        disableds.value = false
    }
}
const check_data = ref({
    note: '',//备注
    name: '',//医生名称
    day: 1,//查房天数
    detart: '',//科室
    temperature: '',//体温
    breathe: '',//呼吸
    blood: '',//血压
    rate: '',//心率
    reason: '',//住院原因
})
const click = (item, indexs) => {
    if (indexs != 0) index.value = indexs
    for (let i in check_list_value.value) {
        if (check_list_value.value[i].check_time == item.timestamp) {
            check_data.value = JSON.parse(JSON.stringify(check_list_value.value[i]))
            id.value = JSON.parse(JSON.stringify(check_list_value.value[i].id))
        }
    }
}
const Settlement = (item, indexs) => {
    loadings.value = true
    if (indexs != 0) day.value = indexs
    Settlements()
}
function returned() {
    stated.value = true
    defaults.value = false
    loadings.value = false
    zhangdetailed.value = []
}
// 查房保存
const save = () => {
    check_add({
        room_id: check_data.value.room_id,
        name: check_data.value.name,
        temperature: check_data.value.temperature,
        breathe: check_data.value.breathe,
        rate: check_data.value.rate,
        blood: check_data.value.blood,
        note: check_data.value.note,
        check_time: check_data.value.check_time,
        detart: check_data.value.detart,
        card: check_data.value.card,
        day: check_data.value.day,
        bed: check_data.value.bed,
        id: check_data.value.id
    }).then((res) => {
        if (res.code == 1) {
            ElMessage({
                type: 'success',
                message: '保存成功',
            });
            check_list({ card: card.value, room_id: room_idd.value, bed: bed_num.value }).then((res) => {
                res.data = res.data.sort((a, b) => {
                    return a.day - b.day
                })
                let array = [{
                    content: '住院',
                    timestamp: res.data[0].check_time
                }];
                for (let i in res.data) {
                    array.push({
                        content: '第' + res.data[i].day + '次查房',
                        timestamp: res.data[i].check_time,
                        type: 'primary',
                        hollow: true,
                    })
                }
                activities.value = array
                check_list_value.value = res.data
                check_data.value = res.data[0]
                console.log(check_data.value, 9999);
            })
            // box()
        } else {
            ElMessage({
                type: 'err',
                message: res.msg,
            });
        }
    })
}
// 查房恢复
const restore = () => {
    check_data.value = JSON.parse(JSON.stringify(check_list_value.value[index.value - 1]))
    ElMessage({
        type: 'success',
        message: '恢复成功',
    });
}
// 查房重置
const reset = () => {
    ElMessage({
        type: 'success',
        message: '重置成功',
    });
    check_data.value = []
}
const room = (e) => {
    value.value = e
}
const box = () => {
    try {
        depart().then((res) => {
            console.log(res);
            for (const dataItem of res.data) {
                options.value.push({ value: dataItem.id, label: dataItem.name });
            }
        })
        room_list().then((res) => {
            console.log(res, 123);
            search_value.value = res.data
            room_value.value = res.data
            loadinng.value = false
        })
        visit().then((res) => {
            console.log(res, 98989);
            visit_data.value = res.data
        })
    } catch {
        loadinng.value = false
    }
}
const clocks = (delid) => {
    ElMessageBox.confirm('是否确认删除?', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            Settlement_del({
                id: delid
            }).then((res) => {
                console.log(res);
                if (res.code == 1) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    });
                    box()
                } else {
                    ElMessage({
                        type: 'error',
                        message: '删除失败',
                    });
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            });
        });
};

// 编辑
function centerDialogVisible(mxid, mxdata) {
    title.value = '编辑'
    centerDialogVisibles.value = true
    zangxid.value = mxid
    ruleForm.value.region = parseInt(mxdata.name_id)
    prices_name.value = mxdata.price
    if (bianvalue.value != '' || bianvalue.value != undefined) {
        prices_all.value = bianvalue.value * prices_name.value
    }
    ruleForm.value.name = `${mxdata.type}`
    if (ruleForm.value.name == 1) {
        drap()
        ruleForm.value.count = mxdata.number
        disableds.value = false
    } else {
        tix()
        disableds.value = false
        ruleForm.value.count = mxdata.number
    }
    ruleForm.value.date1 = `${mxdata.status}`
    inp_zj.value = true
}
// 取消
const resetForm = (formEl) => {
    if (!formEl) return;
    prices_name.value = ''
    inp_zj.value = false
    ruleForm.value = (
        {
            name: '',
            region: '',
            count: '',
            date1: '',
        }
    )
    setTimeout(() => {
        formEl.clearValidate();
    }, 10);
    centerDialogVisibles.value = false
};
const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            Settlement_add({
                day: day.value,
                card: check_list_value.value[index.value].card,
                bed: check_list_value.value[index.value].bed,
                room_id: check_list_value.value[index.value].room_id,
                name_id: ruleForm.value.region,
                price: prices_name.value,
                money: prices_all.value,
                number: ruleForm.value.count,
                type: ruleForm.value.name,
                status: ruleForm.value.date1,
                id: zangxid.value || ''
            }).then((res) => {
                console.log(res);
                if (res.code == 1) {
                    ElMessage({
                        message: `${res.msg}`,
                        type: 'success',
                    })
                    Settlements()
                    box()
                    centerDialogVisibles.value = false
                    ruleForm.value = (
                        {
                            name: '',
                            region: '',
                            count: '',
                            date1: '',
                        }
                    )
                    setTimeout(() => {
                        formEl.clearValidate();
                    }, 10);
                } else {
                    ElMessage({
                        message: `${res.msg}`,
                        type: 'error',
                    })
                }
            })
        } else {
            console.log('error submit!', fields);
        }
    });
};
// 添加
function add() {
    title.value = '添加'
    centerDialogVisibles.value = true
    prices_all.value = ''
    prices_name.value = ''
    disableds.value = true
}
function removeDuplicates(arr, key) {
    const seen = new Set();
    return arr.filter(obj => {
        const value = obj[key];
        if (seen.has(value)) {
            return false;
        }
        seen.add(value);
        return true;
    });
}
// 结算按钮
const settlement = (item) => {
    console.log(item, 2222);
    settlement_status.value = true
    visit_details(item)
    card.value = item.card
    room_id.value = item.id
    bed.value = item.bed_num
    bed_num.value = item.bed_num
    room_num.value = item.room_num
    Settlement_list({ card: item.card, room_id: item.id, bed: item.bed_num }).then((res) => {
        console.log(res);
        let array = [{
            content: '住院',
            timestamp: res.data[0].create_time
        }];
        for (let i in res.data) {
            array.push({
                content: '第' + res.data[i].day + '天',
                timestamp: res.data[i].create_time,
                type: 'primary',
                hollow: true,
            })
        }
        activities.value = removeDuplicates(array, 'content');
        check_list_value.value = res.data
        check_data.value = res.data[0]
        Settlements()
    })
}
const Settlements = () => {
    console.log(day.value, 12423);
    Settlement_list({ card: card.value, room_id: room_id.value, bed: bed.value, day: day.value }).then((res) => {
        setTimeout(() => {
            loadings.value = false
            zhangdetailed.value = res.data
        }, 500)
    })
    loadings.value = false
}
const detart_name = ref();
const room_idd = ref()
// 查房按钮
const check = (item) => {
    room_idd.value = item.id
    bed_num.value = item.bed_num
    card.value = item.card
    check_data.value.reason = item.reason
    form.reason = item.reason
    console.log(item);
    detart_name.value = item.detart_name
    room_num.value = item.room_num
    check_status.value = true
    visit_details(item)
    check_list({ card: item.card, room_id: item.id, bed: item.bed_num }).then((res) => {
        res.data = res.data.sort((a, b) => {
            return a.day - b.day
        })
        let array = [{
            content: '住院',
            timestamp: res.data[0].check_time
        }];
        for (let i in res.data) {
            array.push({
                content: '第' + res.data[i].day + '次查房',
                timestamp: res.data[i].check_time,
                type: 'primary',
                hollow: true,
            })
        }
        activities.value = array
        check_list_value.value = res.data
        check_data.value = res.data[0]
        console.log(check_data.value, 9999);
    })
}
function visit_details(item) {
    console.log(item, 999999999);
    visit_detail({ card: item.card }).then((res) => {
        console.log(res.data, 124);
        res.data.avatar = 'https://lxt.jingyi.icu' + res.data.avatar
        visit_value.value = res.data
    })
}
box()
//搜索
const seach = () => {
    let obj = {}
    obj = {
        department: depart_value.value,
        room_num: room_select.value,
        bed_num: bed_select.value,
        room_status: value.value
    }
    //排除空
    for (let key in obj) {
        if (obj[key] == '' || obj[key] == null) {
            delete obj[key]
        }
    }
    //@param condition 过滤条件
    //@param data 需要过滤的数据
    let filter = (condition, data) => {
        return data.filter(item => {
            return Object.keys(condition).every(key => {
                return String(item[key]).toLowerCase().includes(
                    String(condition[key]).trim().toLowerCase())
            })
        })
    }
    let data = filter(obj, search_value.value)
    if (data != '') {
        room_value.value = data
    } else {
        room_value.value = []
    }
}
</script>
<style lang="scss" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #006EFF;
}

.barground {
    width: 110px;
    padding-top: 10px;
    height: 50px;
}

.button {
    position: absolute;
    right: 0px;
    top: 40px;
}

.note {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-left: 60px;
    margin-top: 40px;
    position: relative;
    padding-bottom: 20px;
}

.note p {
    width: 450px;
    display: flex;
    align-items: center;
}

.note span {
    width: 100px;
    display: block;
    color: #AFAFAF;
}

.form {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-left: 60px;
}

.form p {
    width: 250px;
    display: flex;
    align-items: center;
}

.form span {
    color: #AFAFAF;
}

.forms {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-top: 40px;
    margin-left: 60px;
}

.forms p {
    width: 300px;
    display: flex;
    align-items: center;
}

.forms span {
    color: #AFAFAF;
}

.bar {
    background-color: #EFF6FF;
    border-right: 5px solid blue;
}

.room_box {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    // justify-content: space-between;
    margin-left: 0.5%;
}

.but {
    width: 70px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    height: 90px;
    align-items: center;
}

.but div {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.room_list {
    width: 24%;
    display: flex;
    padding: 10px;
    align-items: center;
    height: 100px;
    border: 1px solid #f4f4f4;
    margin-right: 1%;
    justify-content: center;
    margin-bottom: 1%;
}

.room_list img {
    width: 80px;
    height: 80px;
    border-radius: 5px;
}

.box-card {
    width: 100%;
}

.user_inp {
    width: 33.33%;
    display: flex;
    align-items: center;
}

.arrow {
    width: 96%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-left: 3%;
    height: 7vh;
}

.room_zhong {
    width: 170px;
    display: flex;
    align-items: center;
    margin: 0px 10px;
    flex-wrap: wrap;
    padding-top: 20px;
}

.room_zhong p {
    width: 100%;
}

.room_top {
    display: flex;
}

.room_zhong span {
    margin-right: 7px;
}

.room_zhong div {
    display: flex;
    width: 100%;
    justify-content: space-around;
}

//上传
.avatar-uploader {
    border: 1px dashed var(--el-border-color) !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    display: flex;
    align-items: center;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

//上传
.form_word {
    margin-right: 20px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>